/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util'
import { deleteAction, getAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import TokenStorageUtil from "../utils/TokenStorageUtil";

export const YcListMixin = {
  props: {
    initSelectedKeys: {
      type: Array,
      default: () => []
    },
    initSelectedRows: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      //token header
      tokenHeader: { 'X-Access-Token': TokenStorageUtil.get() },
      rowKey: 'id',
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 100,
        pageSizeOptions: ['10', '20', '50', '100', '200', '500'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + this.$t('m.common.label.page_record_num',[total])
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      selectedRowKeys: [],
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      /** 高级查询拼接方式 */
      superQueryMatchType: 'and',
    }
  },
  watch: {
    initSelectedKeys: {
      handler(value) {
        this.selectedRowKeys = value
      },
      immediate: true
    },
    initSelectedRows: {
      handler(value) {
        this.selectionRows = value
      },
      immediate: true
    },
    selectedRowKeys: {
      handler(value) {
        this.$emit("setSelectedRowKeys", value)
      }
    },
    selectionRows: {
      handler(value) {
        this.$emit("setSelectionRows", value)
      }
    }
  },
  created () {
    // FK 初始化外键
    if (typeof this.createdFk == 'function') {
      this.createdFk()
    }

    if (!this.disableMixinCreated) {
     // //console.log(' -- mixin created -- ')
      this.loadData()
      //初始化字典配置 在自己页面定义
      this.initDictConfig()
    }
  },
  methods: {
    onSearch(value) {
      if (value) {
        this.queryParam['keyWord'] = value
      } else {
        delete this.queryParam['keyWord']
      }
      this.loadData()
    },
    loadData (arg) {
      if (!this.url.list) {
        this.messageUtil.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams()//查询条件

      // FK 外键查询
      if (typeof this.getFkParams == 'function') {
        params = this.getFkParams(params)
      }

      this.loading = true
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total

          this.afterLoad()

          // FK 根据外键刷新
          if (typeof this.loadFk == 'function') {
            this.loadFk(this.dataSource)
          }

        }else {
          this.messageUtil.warning(res.message)
        }
        this.loading = false
      })
    },
    afterLoad () {
    },
    initDictConfig () {
     // //console.log('--这是一个空方法!')
    },
    handleSuperQuery (params, matchType) {
      //高级查询方法
      if (!params) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(params)
        this.superQueryMatchType = matchType
      }
      this.loadData(1)
    },
    getQueryParams () {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField () {
      //TODO 字段权限控制
      var str = 'id,'
      this.columns.forEach(function (value) {
        str += ',' + value.dataIndex
      })
      return str
    },

    onSelectChange (selectedRowKeys, selectionRows) {
      // this.selectedRowKeys = selectedRowKeys
      // this.selectionRows = selectionRows

      this.selectedRowKeys = selectedRowKeys
      const aa = this.selectionRows.filter(item => selectedRowKeys.indexOf(item[this.rowKey]) !== -1);
      const bb = aa.map(row => row[this.rowKey]);
      const cc = selectionRows.filter(item => bb.indexOf(item[this.rowKey]) === -1);
      this.selectionRows = [...aa, ...cc];
    },
    onClearSelected () {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    clear () {
      this.onClearSelected()
      this.dataSource = []
      this.ipagination.total = 0
      this.ipagination.current = 1
    },
    searchQuery () {
      this.loadData(1)
      this.onClearSelected();
    },
    superQuery () {
      this.$refs.superQueryModal.show()
    },
    searchReset () {
      this.queryParam = {}
      this.loadData(1)
      this.onClearSelected();
    },
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.messageUtil.error('请设置url.deleteBatch属性!')
        return
      }
      this.batchDelByUrl(this.url.deleteBatch)
    },
    batchDelByUrl: function (url) {
      if (this.selectedRowKeys.length <= 0) {
        this.messageUtil.warning(this.$t('m.common.tip.select_one_warn'))
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: this.$t('m.common.title.delete'),
          content: this.$t('m.common.tip.delete_confirm2',[this.selectedRowKeys.length]) + (this.delTip ? this.delTip : ''),
          onOk: function () {
            that.loading = true
            deleteAction(url, { ids: ids }).then((res) => {
              if (res.success) {
                that.messageUtil.success(res.message)
                that.loadData()
                that.onClearSelected()
                that.afterBatchDel()
              } else {
                that.messageUtil.warning(res.message)
              }
            }).finally(() => {
              that.loading = false
            })
          }
        })
      }
    },
    afterBatchDel () {
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.messageUtil.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          that.messageUtil.success(res.message)
          that.loadData()
          that.afterHandleDelete()
        } else {
          that.messageUtil.warning(res.message)
        }
      })
    },
    afterHandleDelete () {
    },
    handleEdit: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = this.$t('m.common.title.update')
      this.$refs.modalForm.disableSubmit = false
    },
    handleAdd: function () {
      this.$refs.modalForm.add()
      this.$refs.modalForm.title = this.$t('m.common.title.add')
      this.$refs.modalForm.disableSubmit = false
    },
    handleTableChange (pagination, filters, sorter) {
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleToggleSearch () {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    // 给popup查询使用(查询区域不支持回填多个字段，限制只返回一个字段)
    getPopupField (fields) {
      return fields.split(',')[0]
    },
    modalFormOk () {
      // 新增/修改 成功时，重载列表
      this.loadData()
    },
    handleDetail: function (record) {
      this.$refs.modalForm.edit(record)
      this.$refs.modalForm.title = this.$t('m.common.title.detail')
      this.$refs.modalForm.disableSubmit = true
    },
    /* 导出 */
    handleExportXls2 () {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${bootConfig[process.env.NODE_ENV].VUE_APP_API}${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },
    handleExportXls (fileName) {
      if (!fileName || typeof fileName != 'string') {
        fileName = '导出文件'
      }
      let param = { ...this.queryParam }
      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      //console.log('导出参数', param)
      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.messageUtil.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
        }
      })
    },
    /* 导入 */
    handleImportExcel (info) {
      if (info.file.status !== 'uploading') {
        //console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          // this.messageUtil.success(`${info.file.name} 文件上传成功`);
          if (info.file.response.code === 201) {
            let { message, result: { msg, fileUrl, fileName } } = info.file.response
            let href = bootConfig[process.env.NODE_ENV].VUE_APP_API + fileUrl
            this.$warning({
                title: message,
                content: (
                  < div >
                  < span > { msg } < /span><br/ >
                  < span > 具体详情请 < a href = { href } target = '_blank' download = { fileName } > 点击下载 < /a> </span >
              < /div>
            )
          })
          } else {
            this.messageUtil.success(info.file.response.message || `${info.file.name} `+this.$t('m.common.tip.file_upload_sucess') )
          }
          this.loadData()
        } else {
          this.messageUtil.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.messageUtil.error(this.$t('m.common.tip.file_upload_error') +`: ${info.file.msg} `)
      }
    },
    /* 图片预览 */
    getImgView (text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return getFileAccessHttpUrl(text)
    },
    /* 文件下载 */
    uploadFile (text) {
      if (!text) {
        this.messageUtil.warning('未知的文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      let url = getFileAccessHttpUrl(text)
      window.open(url)
    },
    clickThenCheck (record) {
      return {
        on: {
          click: () => {
            if (this.radio) {
              this.onSelectChange(record[this.rowKey].split(','), [record])
              this.$nextTick(() => {this.$emit('selected')})
            } else {
              const keys = this.selectedRowKeys.filter(vo => vo !== record[this.rowKey])
              if (keys.length < this.selectedRowKeys.length) {
                const rows = this.selectionRows.filter(vo => vo[this.rowKey] !== record[this.rowKey])
                this.selectedRowKeys = keys
                this.selectionRows = rows
              } else {
                this.selectedRowKeys = [...this.selectedRowKeys, record[this.rowKey]]
                this.selectionRows = [...this.selectionRows, record]
              }
            }
          }
        }
      }
    }
  }

}
